package com.qdxwx.manage.controller.order;

import com.qdxwx.common.exception.AccountException;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.page.TableDataInfo;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.account.UserAccountDetailService;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.data.service.coupon.CouponCodeService;
import com.qdxwx.data.service.order.OrderDetailService;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.data.service.user.UserInviteService;
import com.qdxwx.data.service.user.UserLetterService;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.account.UserAccountDetail;
import com.qdxwx.models.coupon.CouponCode;
import com.qdxwx.models.enums.*;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.order.Order;
import com.qdxwx.models.order.OrderDetail;
import com.qdxwx.models.order.OrderDetailQuery;
import com.qdxwx.models.order.OrderQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 课程订单Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CouponCodeService couponCodeService;
    @Autowired
    private UserInviteService userInviteService;
    @Autowired
    private UserLetterService userLetterService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private UserAccountDetailService userAccountDetailService;

    @Permissions("order:list")
    @GetMapping("/list.html")
    public String list(HttpServletRequest request, ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error500;
        long userId = TKConvert.toLong(request.getParameter("userId"));
        mmap.put("userId", userId);
        mmap.put("manager", manager);
        return "order/order-list";
    }

    /**
     * 查询课程订单列表
     */
    @Permissions("order:list")
    @PostMapping("/list.json")
    @ResponseBody
    public TableDataInfo list(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) {
            return TableDataInfo.error("未登录！");
        }
        int companyId = TKConvert.toInteger(request.getParameter("companyId"));
        long userId = TKConvert.toLong(request.getParameter("userId"));
        OrderQuery order = new OrderQuery();
        order.setOrderNo(request.getParameter("orderNo"));
        order.setOrderType(request.getParameter("orderType"));
        order.setStatus(request.getParameter("status"));
        order.setUserId(userId);
        if (companyId > 1) {
            order.setCompanyId(companyId);
        }
        List<Order> list = orderService.getList(order, PageRequest.form(request));
        int count = orderService.count(order);
        return TableDataInfo.success(list, count);
    }


    /**
     * 取消或恢复订单
     */
    @PostMapping("/status.json")
    @ResponseBody
    public AjaxResult status(HttpServletRequest request) {
        int orderId = TKConvert.toInteger(request.getParameter("orderId"));
        if (orderId < 1) return error("参数缺少id");
        Order order = orderService.get(orderId);
        if (order == null) return error("找不到指定数据");
        order.setStatus(request.getParameter("status"));
        int row = orderService.updateOrder(order);
        if (row > 0) {
            //优惠券恢复
            CouponCode couponCodeTemp = couponCodeService.get(order.getCouponCodeId());
            if (couponCodeTemp != null && couponCodeTemp.getStatus() == 6 && order.getStatus().equals("CANCEL")) {//冻结才修改
                couponCodeTemp.setStatus(1);//1未使用
                couponCodeTemp.setOrderNo("");
                couponCodeTemp.setOrderId(0);
                couponCodeService.update(couponCodeTemp);
            }
            //发送站内信
            LetterTemplate letterTemplate = LetterTemplate.ORDER_CANCEL;
            if (order.getStatus().equals(OrderStatus.INIT.toString())) {
                letterTemplate = LetterTemplate.ORDER_RECOVER;
            }
            userLetterService.send(order.getUserId(), letterTemplate, order.getOrderNo());
        }
        return toAjax(row);
    }


    /**
     * 后台审核开通
     */
    @PostMapping("/open.json")
    @ResponseBody
    public AjaxResult auditing(HttpServletRequest request) throws Exception {
        Manager manager = SessionUtils.getManager();
        if (manager == null) {
            return error("登录超时！");
        }
        if (manager.getCompanyId() != 1) {
            return error("无操作权限！");
        }
        String orderNo = TKString.queryKey(request.getParameter("orderNo"));
        if (TKString.isEmpty(orderNo)) {
            return error("缺少订单号");
        }
        Order order = orderService.getByOrderNo(orderNo);
        if (order == null) {
            return error("找不到指定数据");
        }
        if (OrderStatus.SUCCESS.toString().equals(order.getStatus())) {
            logger.info("已支付成功，不需要再进行操作！orderId:" + order.getOrderId());
            return AjaxResult.success();//已成功，直接返回
        }
        if (!OrderStatus.INIT.toString().equals(order.getStatus())) {
            logger.error("订单状态异常！orderId:" + order.getOrderId());
            return AjaxResult.error("订单状态异常");
        }
        //支付方式
        order.setPayType(PayType.FREE.toString());
        if (OrderType.ACCOUNT.equals(order.getOrderType())) {
            // 每次充值都有out_trade_no，防止重复充值做查询判断
            // 查询账户历史是否用out_trade_no，如果有了。抛出异常
            UserAccountDetail accountHistory = userAccountDetailService.getByOrderId(order.getOrderId(), order.getUserId());
            if (accountHistory != null) {
                logger.error("此订单已存在资金操作记录！orderId:" + order.getOrderId());
                throw new AccountException("此订单已存在资金操作记录！");
            }
            UserAccount userAccount = userAccountService.getByUserId(order.getUserId());
            userAccountService.income(userAccount, order.getCashAmount(), AccountType.VM, AccountHistoryType.CASHLOAD, order.getOrderId(), "支付充值", true, AccountBizType.CASH);//充值订单
        }
        order.setStatus(OrderStatus.SUCCESS.toString());
        order.setPayTime(LocalDateTime.now());
        try {
            orderService.updateOrderStatusSuccess(order);
            if (!OrderType.MEMBER.equals(order.getOrderType())) {
                //分销消费返现
                userInviteService.orderCashback(request, order);
            }
            //发送站内信
            userLetterService.send(order.getUserId(), LetterTemplate.ORDER_OPEN, order.getOrderNo());
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("cancelOrRegain-error", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 退费 ：修改订单和流水状态
     */
    @PostMapping("/refund.json")
    @ResponseBody
    public AjaxResult refund(HttpServletRequest request) {
        int orderId = TKConvert.toInteger(request.getParameter("orderId"));
        if (orderId < 1) return error("缺少参数id");
        int refundAmount = Double.valueOf(TKConvert.toDouble(request.getParameter("refundAmount")) * 100).intValue();
        if (refundAmount <= 0) return error("退款金额必选大于0元");
        Order order = orderService.get(orderId);
        if (order == null) return error("找不到指定订单");
        if (!order.getStatus().equals(OrderStatus.SUCCESS.toString())) {
            return error("操作失败，支付成功的订单，才能退款哦！");
        }
        order.setStatus(OrderStatus.REFUND.toString());
        order.setDescription(request.getParameter("description"));
        order.setRefundAmount(refundAmount);
        int row = orderService.updateOrder(order);
        if (row > 0) {
            // 记录订单操作记录
            OrderDetailQuery query = new OrderDetailQuery();
            query.setOrderNo(order.getOrderNo());
            // 获取订单下的流水列表
            List<OrderDetail> detailList = orderDetailService.getList(query);
            if (detailList.size() > 0) {
                for (OrderDetail orderDetail : detailList) {
                    orderDetail.setAuthStatus(OrderStatus.REFUND.toString());
                    orderDetail.setDescription(order.getDescription());
                    orderDetail.setUpdateTime(LocalDateTime.now());
                    orderDetailService.update(orderDetail);
                }
            }
            //发送站内信
            userLetterService.send(order.getUserId(),  LetterTemplate.ORDER_REFUND, order.getOrderNo());
            //退款入账
            UserAccount userAccount = userAccountService.getByUserId(order.getUserId());
            userAccountService.income(userAccount, order.getRefundAmount(), AccountType.VM, AccountHistoryType.ADMINLOAD, 0, "订单退款入账", true, AccountBizType.ADMIN);
        }
        return toAjax(row);
    }
}